//
//  FollowAlertV.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/11/4.
//  Copyright © 2025 aowang. All rights reserved.
//  跟随弹窗控件

import UIKit
import Kingfisher
let itemCWidthxx = (KSGlobal.screenW - 50)/(PlatformManager.shared.platform == .zhuYouAn ? 3 : 4) - 1
let itemCHeightxx = PlatformManager.shared.platform == .zhuYouAn ? ((KSGlobal.screenW - 50)/3)*0.7 - 1 : (KSGlobal.screenW - 50)/4 - 1


class FollowAlertV:UIView,AlertSystemAnimationProtocol,UICollectionViewDataSource,UICollectionViewDelegate {
    private var alertItemArr = [MenuItem]()// 上部分 弹出数组
    private func getHeight() -> CGFloat {
        var hang:CGFloat = CGFloat((alertItemArr.count - 1)/(PlatformManager.shared.platform == .zhuYouAn ? 3 : 4) + 1)
        if  hang < 1 {
            hang = 1
        }
        if PlatformManager.shared.platform != .zhuYouAn {
            if  hang > 4 {
                hang = 4
            }
        }
        return itemCHeightxx * hang + 20
        
    }
    // 用来匹配目录名称，控制小箭头上下展示
    var alertDirectory = ""
    var superVC:UIViewController!
    var collectionView: UICollectionView!
    private var radiusMask: CAShapeLayer?
    // 父控件  数据源  镂空坐标   弹出方向
    func setDataArrAndAlert(alertDirectory:String = "", superVC: UIViewController, arr: [MenuItem], loukong: CGRect, derection: ADerection, didRemove: (() -> ())? = nil) {
        self.superVC = superVC
        self.alertItemArr = arr
        self.alertDirectory = alertDirectory
        self.collectionView.reloadData()
        var hhhhhh = self.getHeight()
        if derection == .top {
            
            if PlatformManager.shared.platform == .zhuYouAn {
                hhhhhh = min(hhhhhh, loukong.origin.y)
            }
            
            self.constrains { make in
                make.top.equalToSuperview().offset(loukong.origin.y - hhhhhh)
                make.left.equalToSuperview().offset(10)
                make.right.equalToSuperview().offset(-10)
                make.height.equalTo(hhhhhh)
            }
        } else {
            
            if PlatformManager.shared.platform == .zhuYouAn {
                hhhhhh = min(hhhhhh, KSGlobal.screenH - (loukong.origin.y + loukong.size.height))
            }
            
            self.constrains { make in
                make.top.equalToSuperview().offset(loukong.origin.y + loukong.height)
                make.left.equalToSuperview().offset(10)
                make.right.equalToSuperview().offset(-10)
                make.height.equalTo(hhhhhh)
            }
        }
        
        if PlatformManager.shared.platform == .zhuYouAn {
            if radiusMask != nil {
                radiusMask?.removeFromSuperlayer()
                radiusMask = nil
            }
            
            var path: UIBezierPath
            
            if KS_SCREEN_WIDTH - loukong.maxX < 30 {
                // 是最右边的 item 展开
                if derection == .top {
                    path = UIBezierPath(roundedRect: CGRect(origin: .zero, size: CGSize(width: KS_SCREEN_WIDTH - 2*10, height: hhhhhh)), byRoundingCorners: [.topLeft, .topRight, .bottomLeft], cornerRadii: CGSize(width: 8, height: 8))
                } else {
                    path = UIBezierPath(roundedRect: CGRect(origin: .zero, size: CGSize(width: KS_SCREEN_WIDTH - 2*10, height: hhhhhh)), byRoundingCorners: [.topLeft, .bottomLeft, .bottomRight], cornerRadii: CGSize(width: 8, height: 8))
                }
                
            } else {
                path = UIBezierPath(roundedRect: CGRect(origin: .zero, size: CGSize(width: KS_SCREEN_WIDTH - 2*10, height: hhhhhh)), byRoundingCorners: [.topLeft, .topRight, .bottomLeft, .bottomRight], cornerRadii: CGSize(width: 8, height: 8))
            }
            radiusMask = CAShapeLayer()
            radiusMask?.path = path.cgPath
            layer.mask = radiusMask
            layer.borderColor = UIColor.clear.cgColor
        }
  
        self.presentS(loukong, direction: derection, didRemove: didRemove)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        let layout = UICollectionViewFlowLayout()
        layout.footerReferenceSize = CGSize(width: 0,height: 0)
        layout.sectionInset = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: 0)
        layout.minimumLineSpacing = 1
        layout.minimumInteritemSpacing = 0.5
        
        layout.itemSize = CGSize(width: itemCWidthxx, height: itemCHeightxx)
        layout.scrollDirection = .vertical
        
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        self.addSubview(collectionView)
        collectionView.backgroundColor =  Theme.pureWhite()
        collectionView.register(FollowALCell.self, forCellWithReuseIdentifier: FollowALCell.identifier)
        collectionView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom:  10, right: 10)
        collectionView.snp.makeConstraints { make in
            make.left.equalTo(self)
            make.top.equalTo(self)
            make.bottom.right.equalTo(self)
        }
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         return self.alertItemArr.count
     }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FollowALCell.identifier, for: indexPath as IndexPath) as! FollowALCell
        
        let onex = self.alertItemArr[indexPath.row]
        let titleS = self.alertItemArr[indexPath.row].title.unwrap
        cell.setTitle(titleS)
        if let img = UIImage(named: "\(titleS)_t") {
            cell.img.image = img
        } else  if let imageUrl = URL(string: onex.imgUrl.unwrap) {
            let resource = KF.ImageResource(downloadURL: imageUrl)
            cell.img.kf.setImage(with: resource, placeholder: UIImage(named:"1_ld"))
        } else {
            cell.img.image = UIImage(named:"new_img\(indexPath.row%5 + 1)")
        }
 
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        self.dismiss()
        let one =  self.alertItemArr[indexPath.row].enterFunc!
        one(self.superVC)
        
        
    }
    
    
    
    
    
}

class FollowALCell: UICollectionViewCell {
   
   var img: UIImageView = {
       let img = UIImageView()
       return img
   }()
  private var title: UILabel = {
       let lab :UILabel = UILabel()
       lab.textColor = UIColor(kshex: "#808080")
       lab.font = UIFont.boldSystemFont(ofSize: 13)
       lab.numberOfLines = 2
       lab.textAlignment = .center
       return lab
   }()
   //  ▲  ▴ ▾
   var hasSubTriangle: UILabel = {
       let v = UILabel()
       v.text = "▾"
       v.font = UIFont.systemFont(ofSize: 24)
       v.isHidden = true
       v.textColor = UIColor(kshex: "#aaaaaa")
       return v
   }()
   func setTitle(_ str:String) {
    
       title.text = str
   }
   
   convenience required init(coder : NSCoder){
       self.init()
   }

   override init(frame: CGRect) {
       super.init(frame: frame)
       self.initUtil()
   }
   
   func initUtil() {
       self.backgroundColor = Theme.pureWhite()

       
    
       self.addSubview(img)
  
       
       img.snp.makeConstraints { (make) in
           make.centerX.equalTo(self)
           make.bottom.equalTo(self.snp.centerY).offset(6)
           make.width.equalTo(self).multipliedBy(0.38)
           make.height.equalTo(img.snp.width)
            
     
           
       }
       
       self.addSubview(title)
       title.snp.makeConstraints { (make) in
           make.centerX.equalTo(self)
           make.top.equalTo(img.snp.bottom).offset(5)
           make.left.right.equalTo(self)
       }
       self.addSubview(hasSubTriangle)
       hasSubTriangle.snp.makeConstraints { (make) in
           make.top.equalTo(self).offset(1)
           make.right.equalTo(self).offset(-1)
           make.width.equalTo(10)
           make.height.equalTo(10)
         
       }
       
   }
}
